import {
    useMutation,
    UseMutationOptions,
    useQuery, useQueryClient,
    UseQueryOptions
} from "@tanstack/react-query";
import axios, {AxiosError} from "axios";
import {useAccountStore} from "../store/store";
import {useNavigate} from "react-router-dom";
import {message} from "antd";


export const useLogin = (
    options: UseMutationOptions<{ jwt?: string; message?: string }, AxiosError<ApiResponse>, { username: string; password: string }> = {}
) => {

    return useMutation(
        async ({username, password}) => {
            const resp = await axios.post('/account/login', {
                username,
                password
            }).catch((err) => {
                return err;
            });
            return resp.data ? resp.data : resp;
        },
        options
    );
}


export const useAccountSave = (
    options: UseMutationOptions<ApiResponse, AxiosError<ApiResponse>, AccountDTO> = {}
) => {
    const queryClient = useQueryClient();

    return useMutation(
        async (account) => {
            const resp = await axios.post('/account/save', account).catch((err) => {
                return err;
            });
            return resp.data ? resp.data : resp;
        },
        {
            ...options,
            onSuccess: (data, payload, ...args) => {
                //移除缓存
                queryClient.removeQueries({
                    queryKey: ["useAccountPage"]
                });
                if (data.errorCode != 0) {
                    message.error(data.message);
                }
                if (options.onSuccess) {
                    options.onSuccess(data, payload, ...args);
                }
            }
        }
    );
}


export const useAccountUpdate = (
    options: UseMutationOptions<ApiResponse, AxiosError<ApiResponse>, AccountDTO> = {}
) => {
    const queryClient = useQueryClient();

    return useMutation(
        async (account) => {
            const resp = await axios.post('/account/update', account).catch((err) => {
                return err;
            });
            return resp.data ? resp.data : resp;
        },
        {
            ...options,
            onSuccess: (data, payload, ...args) => {
                //移除缓存
                queryClient.removeQueries({
                    queryKey: ["useAccountPage"]
                });
                queryClient.removeQueries({
                    queryKey: ["useAccountInfo"]
                });
                if (options.onSuccess) {
                    options.onSuccess(data, payload, ...args);
                }
            }
        }
    );
}

export const useAccountUpdatePassword = (
    options: UseMutationOptions<ApiResponse, AxiosError<ApiResponse>, { oldPwd:string,newPwd:string,confirmPwd:string }> = {}
) => {
    const queryClient = useQueryClient();

    return useMutation(
        async (params) => {
            const resp = await axios.post('/account/updatePwd', params).catch((err) => {
                return err;
            });
            return resp.data ? resp.data : resp;
        },
        {
            ...options,
            onSuccess: (data, payload, ...args) => {
                if (options.onSuccess) {
                    options.onSuccess(data, payload, ...args);
                }
            }
        }
    );
}


export const useAccountDelete = (
    options: UseMutationOptions<{ message?: string }, AxiosError<ApiResponse>, any> = {}
) => {
    const queryClient = useQueryClient();
    return useMutation(
        async (id) => {
            const resp = await axios.get('/account/remove/' + id).catch((err) => {
                return err;
            });
            return resp.data ? resp.data : resp;
        },
        {
            ...options,
            onSuccess: (data, payload, ...args) => {
                //移除缓存
                queryClient.removeQueries({
                    queryKey: ["useAccountPage"]
                });
                queryClient.removeQueries({
                    queryKey: ["useAccountInfo"]
                });
                if (options.onSuccess) {
                    options.onSuccess(data, payload, ...args);
                }
            }
        }
    );
}


export const useLogout = () => {
    const accountStore = useAccountStore();
    accountStore.logOut();

    const navigate = useNavigate();
    navigate("/login")
}


export const useAccountPage = (params: any) => {
    return useQuery(["useAccountPage", params], async () => {
        const resp = await axios.post('/account/page', params).catch((err) => {
            return err;
        });
        return resp.data ? resp.data : resp;
    })
}


export const useAccountDetail = (options: UseQueryOptions<ApiResponse & {account:AccountDTO}> = {}) => {
    return useQuery({
        queryKey: ["accountDetail"],
        queryFn: async () => {
            const resp = await axios.get<{ errorCode: number }>('/account/detail').catch((err) => {
                return err;
            });
            return resp.data ? resp.data : resp;
        },
        ...options
    });
}


export const useAccountInfo = (
    accountId: number,
    options: UseQueryOptions<DataResponse<AccountDTO>> = {}
) => {
    return useQuery({
        queryKey: ["useAccountInfo",accountId],
        queryFn: async () => {
            const resp = await axios.get<{ errorCode: number }>('/account/info/' + accountId).catch((err) => {
                return err;
            });
            return resp.data ? resp.data : resp;
        },
        enabled:!!accountId,
        ...options
    });
}
